import React, { useEffect, useState } from 'react';
import styles from './index.module.less';
import ApproveCard from '@/components/card';
import { getMyProcessList } from '@/services/approval';
import { Toast } from 'antd-mobile-v2';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import EmptyLoading from '@/components/empty/empty-loading';
import FilterArea, { OptionsListItem } from '@/components/filter-area';
import moment from 'moment';
import { Prompt } from 'react-router-dom';
import history from '@/utils/history';
import { applyType } from '@/constants';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
// import { APPROVAL_STATUS } from '@/pages/declare/constants';
import { getSearchName } from '@/utils';

// 视窗高度减去减去头部和底部组件的高度
const height =
  document.documentElement.clientHeight -
  (document.documentElement.clientWidth * (40 + 5)) / 375;

const Log: React.FC<RouterProps> = (props) => {
  const defaultPageSize = 10;
  const [pageSize, setPageSize] = useState(defaultPageSize);
  const isMyApply = getSearchName('isMyApply') || '';

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    cacheRouteList: ['/official-doc/detail', '/declare/detail'],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      const isZhiDanState = ['4', '5'].includes(params?.status);
      const reqParams = {
        lastId: params.lastId,
        pageNum: params?.pageNum || 1,
        pageSize: params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize,
        typeList: parseArr(params?.type),
        startDate: params?.time && formatTime(params?.time),
        procStatus: !isZhiDanState ? params?.status : undefined,
        zhiDanState: isZhiDanState ? params?.status : undefined
      };
      const res = await getMyProcessList(reqParams);
      const rows = res.data?.list || [];
      const list = formatData(rows) || [];
      const surplusTotal = res.data?.total - list.length; // 加载完当前请求的数据还剩多少条数据
      setSurplusTotal(surplusTotal < 0 ? 0 : surplusTotal);
      setPageSize(
        params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize
      );
      setData(params?.lastId ? dataSource.concat(list) : list);
      setLastId(list[list.length - 1]?.id);
    }
  });

  const filterData: OptionsListItem[] = [
    {
      label: '状态',
      value: 'status',
      options: [
        { label: '全部', value: undefined },
        // { label: '草稿', value: 0 },
        { label: '审批中', value: 1 },
        { label: '已通过', value: 2 },
        { label: '已拒绝', value: 3 },
        { label: '已撤销', value: 4 }
      ]
    },
    {
      label: '时间',
      value: 'time',
      options: [
        { label: '全部', value: undefined },
        { label: '近3天', value: 3 },
        { label: '近7天', value: 7 },
        { label: '近30天', value: 30 }
      ]
    }
  ];

  const formatTime = (day: number) => {
    return moment()
      .set({ hour: 0, minute: 0, second: 0 })
      .subtract(day, 'days')
      .format('YYYY-MM-DD HH:mm:ss');
  };

  // number和string类型的参数转数组
  const parseArr = (data: number | string | undefined) => {
    if (!data) return undefined;
    if (typeof data === 'number') {
      data = data.toString();
    }
    return data.split(',').map((item) => Number(item));
  };

  const formatData = (data: any[]): any => {
    console.log('data-----------[]', data);
    data?.forEach((item) => {
      switch (item.applyType) {
        case applyType.STOCK_RECEIVE_APPLY:
          item.formData = [
            { label: '划转批次', value: item.lot?.text || '无' },
            {
              label: '业务名称',
              value: item.typeName || item.taskName || '无'
            },
            {
              label: '更新时间',
              value: item?.lastHandlerTime || item.crtTime || '无'
            }
          ];
          break;
        default:
          break;
      }
      item.cardTitle = item.applyName || item.procName || '无';
    });
    return data;
  };

  const handleJump2Detail = (item: any) => {
    if (
      item.applyType === applyType.ONLINE_DOCUMENT_APPLY &&
      item.procStatus === 2
    ) {
      // 已通过的线上公文，进入线下公文详情
      return history.push({
        pathname: `/official-doc/detail/${item.applyId}`,
        query: {
          isMyApply: '1',
          procRecordId: item.procRecordId,
          applyType: applyType.ONLINE_DOCUMENT_APPLY
        }
      });
    }
    history.push({
      pathname: '/declare/detail',
      query: {
        isMyApply: '1',
        applyType: item.applyType,
        innerProcDefId: item.innerProcDefId,
        procRecordId: item.procRecordId,
        applyId: item.applyId,
        // resubmit: item.status !== APPROVAL_STATUS.Draft ? true : false,
        title: item.applyName,
        status: item.procStatus
      }
    });
  };

  return (
    <div className={styles.wrap}>
      <FilterArea
        data={filterData}
        values={searchData}
        onFilterChange={handleSearch}
      />
      {showDom ? (
        <div className={styles.cardList}>
          {dataSource?.length > 0 ? (
            <AntdRefreshList
              height={height}
              initialListSize={pageSize}
              dataSource={dataSource}
              refreshing={refreshing}
              loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div className={styles.cardItem} key={index}>
                  <a onClick={() => handleJump2Detail(item)}>
                    <ApproveCard data={item} hasAvatar withStatus></ApproveCard>
                  </a>
                </div>
              )}
              onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            />
          ) : (
            <EmptyRefresh refreshing={refreshing} onRefresh={handleRefresh} />
          )}
        </div>
      ) : (
        <EmptyLoading />
      )}
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default Log;
